/* eslint-disable default-case */
import React from 'react';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Card, Button, Input, message, Modal, Tabs, List, Avatar } from 'antd';
import moment from 'moment';
import { connect } from 'dva';
import router from 'umi/router';
import queryString from 'query-string';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import messageImg from '@/assets/message.png';
import noticeImg from '@/assets/notice.png';
import annouceImg from '@/assets/annouce.png';
import styles from '@/utils/utils.less';
import Authorized from '@/utils/Authorized';
import { ExclamationCircleOutlined } from '@ant-design/icons';

const FormItem = Form.Item;
const { TabPane } = Tabs;
const { confirm } = Modal;
const { TextArea } = Input;
@Form.create()
@connect(
  ({
    tipnotice = {
      data: {
        list: [],
        pagination: {
          current: 1,
          pageSize: 10,
          total: 0,
        },
      },
      countData: 0,
      activeKey: '1',
    },
    loading,
  }) => ({
    tipnotice,
    loading: loading.effects['tipnotice/fetchAnnounce'] || loading.effects['tipnotice/fetchNotice'],
  })
)
class TipNoticeList extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      annouceVisible: false,
    };
  }

  getListData = (activeKey, current = 1, pageSize = 10) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'tipnotice/updateModelData',
      payload: { activeKey },
    });
    if (Number(activeKey) !== 3) {
      dispatch({
        type: 'tipnotice/fetchNotice',
        payload: {
          currentPage: current,
          pageSize,
          sendType: activeKey,
        },
      });
    } else {
      dispatch({
        type: 'tipnotice/fetchAnnounce',
        payload: {
          pagerArg: {
            currentPage: current,
            pageSize,
          },
        },
      });
    }
  };

  tabChange = value => {
    const { location, dispatch } = this.props;
    router.push({
      pathname: location.pathname,
      query: {
        activeKey: value,
      },
    });
    dispatch({
      type: 'tipnotice/updateModelData',
      payload: { activeKey: value },
    });
    this.getListData(value);
  };

  // 获取消息数量
  getMessageCout = () => {
    const { dispatch } = this.props;
    dispatch({
      type: 'tipnotice/fetchNoticeNum',
      payload: {},
    });
  };

  componentDidMount = () => {
    const {
      location,
      tipnotice: { activeKey },
    } = this.props;
    const activeKeys = queryString.parse(location.search).activeKey || activeKey;
    this.getListData(activeKeys);
    this.getMessageCout();
  };

  handleSign = (sysMsgId, vno) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'tipnotice/fetchSignSuccess',
      payload: { sysMsgId, vno },
    });
  };

  // 跳转页面
  goHref = sysMsgId => {
    const { dispatch } = this.props;
    dispatch({
      type: 'tipnotice/fetchMsgUrl',
      payload: { sysMsgId },
    });
  };

  handleAll = () => {
    const {
      dispatch,
      tipnotice: { activeKey },
    } = this.props;
    dispatch({
      type: 'tipnotice/fetchSignAll',
      payload: { sendType: activeKey, sysId: 4 },
    });
  };

  pubAnnouce = () => {
    this.setState({
      annouceVisible: true,
    });
  };

  // 新增公告
  addAnnouce = values => {
    const { dispatch } = this.props;
    dispatch({
      type: 'tipnotice/fetchAddNotice',
      payload: { ...values },
    }).then(response => {
      if (response.success) {
        message.success(`${response.message || '新增成功！'}`);
        this.setState({
          annouceVisible: false,
        });
        this.getAnnouceList(1, 10);
      } else {
        message.warning(response.message || '服务端错误');
      }
    });
  };

  addOk = () => {
    const { form } = this.props;
    form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        confirm({
          title: '确定要提交吗？',
          icon: <ExclamationCircleOutlined />,
          content: '提交后将自动发布成功，不能再修改删除。',
          onOk: () => {
            this.addAnnouce(values);
          },
          onCancel() {},
        });
      }
    });
  };

  addCancel = () => {
    this.setState({
      annouceVisible: false,
    });
  };

  getIconUrl = sendType => {
    let url = '';
    switch (Number(sendType)) {
      case 1:
        url = messageImg;
        break;
      case 2:
        url = noticeImg;
        break;
      case 3:
        url = annouceImg;
        break;
    }
    return url;
  };

  renderActions = (sendType, item) => {
    switch (Number(sendType)) {
      case 1:
        return [
          Number(item.status) === 2 ? (
            <a onClick={() => this.handleSign(item.sysMsgId, item.vno)}>标记已处理</a>
          ) : (
            <span>已处理</span>
          ),
          <a onClick={() => this.goHref(item.sysMsgId)}>跳转处理</a>,
        ];
      case 2:
        return [
          Number(item.status) === 2 ? (
            <a onClick={() => this.handleSign(item.sysMsgId, item.vno)}>标记已处理</a>
          ) : (
            <span>已处理</span>
          ),
        ];
      default:
        return [];
    }
  };

  render() {
    const {
      loading,
      form: { getFieldDecorator },
      tipnotice: { data, countData, activeKey },
    } = this.props;
    const { annouceVisible } = this.state;
    const pagination = {
      defaultCurrent: 1,
      defaultPageSize: 10,
      current: data.pagination.current,
      pageSize: data.pagination.pageSize,
      total: data.pagination.total,
      showQuickJumper: true,
      showSizeChanger: true,
      onChange: (page, pageSize) => {
        // 页码改变的回调
        this.getListData(activeKey, page, pageSize);
      },
      onShowSizeChange: (current, size) => {
        // 	// 单页条数变化的回调
        this.getListData(activeKey, current, size);
      },
      showTotal: total => {
        const totalPage = total < pagination.pageSize ? 1 : Math.ceil(total / pagination.pageSize);
        return `共 ${total} 条记录 第 ${data.pagination.current} / ${totalPage}页`;
      },
    };
    const tabArr = [
      { key: '1', label: '通知' },
      { key: '2', label: '消息' },
      { key: '3', label: '公告' },
    ];
    const formItemLayout = {
      labelCol: {
        span: 6,
      },
      wrapperCol: {
        span: 16,
      },
    };
    const renderAnnuce = (tabItem, item) => {
      if (Number(tabItem.key) === 3) {
        return (
          <p>
            <span style={{ marginRight: 40 }}>来源：{item.userTypeName}</span>
            创建时间：
            {moment(item.creTime).format('YYYY-MM-DD HH:mm')}
          </p>
        );
      }
      return <p>{moment(item.creTime).format('YYYY-MM-DD HH:mm')}</p>;
    };
    return (
      <PageHeaderWrapper>
        <Card className={styles.tabCard}>
          <Tabs onChange={this.tabChange} activeKey={activeKey}>
            {tabArr.map((tabItem, tabIndex) => {
              const tabCount = countData[tabIndex] ? countData[tabIndex] : 0;
              const tabName =
                Number(tabIndex) === 2 ? `${tabItem.label}` : `${tabItem.label}(${tabCount})`;
              return (
                <TabPane tab={tabName} key={tabItem.key}>
                  {Number(tabItem.key) !== 3 ? (
                    <Button
                      type="primary"
                      style={{ marginBottom: 16 }}
                      onClick={this.handleAll}
                      disabled={Number(tabCount) === 0}
                    >
                      全部处理
                    </Button>
                  ) : (
                    <Authorized authority="mgr:corpNotice:addCorpNotice" noMatch={null}>
                      <Button type="primary" style={{ marginBottom: 16 }} onClick={this.pubAnnouce}>
                        新增公告
                      </Button>
                    </Authorized>
                  )}
                  <List
                    style={{ marginBottom: 16 }}
                    itemLayout="horizontal"
                    dataSource={data.list}
                    bordered
                    pagination={pagination}
                    loading={loading}
                    renderItem={item => (
                      <List.Item actions={this.renderActions(activeKey, item)}>
                        <List.Item.Meta
                          avatar={<Avatar src={this.getIconUrl(activeKey)} />}
                          title={<span>{item.title}</span>}
                          description={
                            <div>
                              <p>{item.content}</p>
                              {renderAnnuce(tabItem, item)}
                            </div>
                          }
                        />
                      </List.Item>
                    )}
                  />
                </TabPane>
              );
            })}
          </Tabs>
          <Modal
            title="新增公告"
            visible={annouceVisible}
            onOk={this.addOk}
            onCancel={this.addCancel}
            destroyOnClose
          >
            <FormItem {...formItemLayout} label="公告标题">
              {getFieldDecorator('title', {
                rules: [{ required: true, message: '请输入公告标题' }],
              })(<Input placeholder="请输入" maxLength={10} />)}
            </FormItem>
            <FormItem {...formItemLayout} label="公告内容">
              {getFieldDecorator('content', {
                rules: [{ required: true, message: '请输入公告内容' }],
              })(
                <TextArea
                  placeholder="请输入不得超过200字的内容"
                  maxLength={200}
                  autosize={{ minRows: 3, maxRows: 6 }}
                />
              )}
            </FormItem>
          </Modal>
        </Card>
      </PageHeaderWrapper>
    );
  }
}
export default TipNoticeList;
